package com.hy.demo.controller;

import com.alibaba.fastjson.JSON;
import com.hy.demo.model.AccessToken;
import com.hy.demo.model.Ticket;
import com.hy.demo.model.UserAccessToken;
import com.hy.demo.model.WeChatUser;
import com.hy.demo.model.response.TicketVO;
import com.hy.demo.util.HttpUtils;
import com.hy.demo.util.WeChatUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


/**
 * 获取关注公众号之后的微信用户信息的接口，如果在微信浏览器里访问
 * https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx088394b051e24bb1&redirect_uri=http%3A%2F%2Fjinlai.free.idcfengye.com%2FweChatLogin%2FloginCheck&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
 * 则这里将会获取到code,之后再可以通过code获取到access_token 进而获取到用户信息
 *
 * redirect_uri要使用urlEncode 编码
 *
 * @author cjl
 * @since  2020-7-24
 * @version 1.0
 */
@Slf4j
@Controller
@RequestMapping("/weChatLogin")
public class WeChatLoginController {

    @Value("${weiXin.appID}")
    public String appId;

    @Value("${weiXin.appSecret}")
    public String appSecret;

    @RequestMapping(value = "/loginCheck", method = { RequestMethod.GET })
    public String doGet(HttpServletRequest request, HttpServletResponse response) {
        // 获取微信公众号传输过来的code,通过code可获取access_token,进而获取用户信息
        String code = request.getParameter("code");
        // 这个state可以用来传我们自定义的信息，方便程序调用，这里也可以不用
        // String roleType = request.getParameter("state");
        log.debug("weChat login code:{}" , code);
        WeChatUser user = null;
        String openId = null;
        if (null != code) {
            UserAccessToken token;
            try {
                // 通过code获取access_token
                token = WeChatUtil.getUserAccessToken(appId,appSecret,code);
                log.debug("weChat login token:{}" , token.toString());
                // 通过token获取accessToken
                String accessToken = token.getAccessToken();
                // 通过token获取openId
                openId = token.getOpenId();
                // 通过access_token和openId获取用户昵称等信息
                user = WeChatUtil.getUserInfo(accessToken, openId);
                log.info("weChat login user:{}" ,user.toString());
                request.getSession().setAttribute("openId", openId);
            } catch (IOException e) {
                log.error("error in getUserAccessToken or getUserInfo or findByOpenId: {}" , e.toString());
                e.printStackTrace();
            }
        }
        // ======todo begin======
        // 前面咱们获取到openId后，可以通过它去数据库判断该微信帐号是否在我们网站里有对应的帐号了，
        // 没有的话这里可以自动创建上，直接实现微信与咱们网站的无缝对接。
        // ======todo end======
//        if (user != null) {
//            // 获取到微信验证的信息后返回到指定的路由（需要自己设定）
//            return "success";
//        } else {
//            return null;
//        }
        return "test";
    }


    /**
     * 页面获取signature
     */
    @RequestMapping("/getTicket")
    @ResponseBody
    public TicketVO getSin() throws IOException {
       AccessToken accessToken= WeChatUtil.getAccessToken(appId,appSecret);
       String token=accessToken.getAccessToken();
       String url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token+"&type=jsapi";
       Connection.Response response=HttpUtils.get(url);
       Ticket ticket;
       try {

           // todo 真实环境 取到ticket 存入到redis中 express设置为7200秒
           ticket= JSON.parseObject(response.body(), Ticket.class);
           String signature;

           //获取nonceStr
           String nonceStr = UUID.randomUUID().toString();

           //获取timestamp
           String timestamp = Long.toString(System.currentTimeMillis() / 1000);


           // 访问页面的url
           String testUrl="http://jinlai.free.idcfengye.com/test.html";

           //将四个数据进行组合，传给SHA1进行加密
           String str = "jsapi_ticket=" + ticket.getTicket() +
                   "&noncestr=" + nonceStr +
                   "&timestamp=" + timestamp +
                   "&url=" + testUrl;

           //sha1加密
           signature = WeChatUtil.SHA1(str);

           TicketVO ticketVO=new TicketVO();
           ticketVO.setAppId(appId);
           ticketVO.setNonceStr(nonceStr);
           ticketVO.setTimestamp(timestamp);
           ticketVO.setSignature(signature);
           System.out.println(ticket);
           System.out.println(ticketVO);
           return ticketVO;
       }catch (Exception e){
           log.error("获取用户ticket失败: {}", e.getMessage());
           return null;
       }

    }
    public static void main(String[] args) {
        // 10位的秒级别的时间戳
        long time1 = 1596615395;
        String result1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time1 * 1000));
        System.out.println("10位数的时间戳（秒）--->Date:" + result1);
    }



}

